package com.zoe.onelink.business.util.ws;

import com.zoe.onelink.business.util.HttpClient;
import com.zoe.onelink.common.enumeration.ExceptionCodeEnum;
import com.zoe.onelink.common.exception.ApiException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>标题: 请求第三方HTTP接口工具类</p>
 * <p>描述: </p>
 * <p>版权: Copyright (c) 2016</p>
 * <p>公司: 智业软件股份有限公司</p>
 *
 * @version: 1.0
 * @author: cxy
 * @date 2016/10/31
 */
@Deprecated
public class HttpRequestUtil {

    private static final Logger logger = LoggerFactory.getLogger(HttpRequestUtil.class);

    /**
     * http请求
     *
     * @param url     请求url前缀
     * @param headers 请求头
     * @param params  请求参数
     */
    public static String doRequest(String url, Map<String, String> headers, Map<String, String> params) throws Exception {
        return doRequest(url, headers, params, 0);
    }

    /**
     * http请求
     *
     * @param url         请求url前缀
     * @param headers     请求头
     * @param params      请求参数
     * @param readTimeOut 超时时间 单位毫秒
     */
    public static String doRequest(String url, Map<String, String> headers, Map<String, String> params, int readTimeOut) throws Exception {
        Map<String, String> header = headers;
        Map<String, String> param = params;
        if (headers == null) {
            header = new HashMap<>(0);
        }
        if (params == null) {
            param = new HashMap<>(0);
        }
        logger.debug("请求地址：{}，请求头：{}, 请求参数{}", url, header.toString(), param.toString());
        String result = null;
        try {

            if (0 == readTimeOut) {
                result = HttpClient.post(url, headers, params);
            } else {
                result = HttpClient.post(url, headers, params, readTimeOut);
            }

        } catch (Exception e) {
            ByteArrayOutputStream buf = new ByteArrayOutputStream();
            e.printStackTrace(new PrintWriter(buf, true));
            buf.close();
            throw ApiException.createEx(ExceptionCodeEnum.HTTP_ERROR, "expMessage", url, header.toString(), param.toString(), e.getMessage());
        }
        return result;

    }
}
